package com.cote.douhahou.pretloan.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.cote.douhahou.pretloan.beans.AppAkomapalendConfigCustomize;
import com.cote.douhahou.pretloan.beans.PersAkomapalendonalInfo;
import com.cote.douhahou.pretloan.level.CircleAkomapalendBarView;
import com.cote.douhahou.pretloan.level.VipAkomapalendInfoActivity;
import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.service.CusServiceAkomapalendDialog;
import com.cote.douhahou.pretloan.service.FbackActivity;
import com.cote.douhahou.pretloan.setting.LogoutActivity;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class PersonalCenterFragment extends Fragment {

    private TextView userNameTextView, userGenderTextView;
    private ImageView userAvatarImageView;
    private View vipBackView;
    private View vipClickView;
    private ImageView vipImageView;
    private TextView vipTextView;
    private ImageView vipNextImageView;
    private CircleAkomapalendBarView vipExpCpb;
    private TextView vipExpDescTextView;
    private View myProfileView, feedbackView, agreementView, settingView;

    public static Bitmap User_Avatar = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal_info, container, false);

        userNameTextView = view.findViewById(R.id.fpca_tv_user_name);
        userGenderTextView = view.findViewById(R.id.fpca_tv_user_gender);
        userAvatarImageView = view.findViewById(R.id.fpca_iv_user_avatar);
        vipBackView = view.findViewById(R.id.fpca_view_vip_bg);
        vipClickView = view.findViewById(R.id.fpca_view_vip_click);
        vipImageView = view.findViewById(R.id.fpca_iv_vip_img);
        vipTextView = view.findViewById(R.id.fpca_tv_vip);
        vipNextImageView = view.findViewById(R.id.fpca_iv_vip_item_right);
        vipExpCpb = view.findViewById(R.id.fpca_cpb_vip_exp);
        vipExpDescTextView = view.findViewById(R.id.fpca_tv_vip_exp_desc);
        myProfileView = view.findViewById(R.id.fpca_view_my_profile);
        feedbackView = view.findViewById(R.id.fpca_view_feedback);
        agreementView = view.findViewById(R.id.fpca_view_privacy_policy);
        settingView = view.findViewById(R.id.fpca_view_setting);

        init(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        HttpHelper.inst().submitEvent("ME","START","");
        HttpHelper.inst().fUSerData(this::refresh);
    }

    private void init(View view){

        view.findViewById(R.id.fpca_ib_customer_service).setOnClickListener(v -> new CusServiceAkomapalendDialog(requireContext()).show());

        //my profile
        vipClickView.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("ME","VIP_INFO_CLICK","");
            startActivity(new Intent(requireContext(), VipAkomapalendInfoActivity.class));
        });
        myProfileView.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("ME","MY_PROFILE_CLICK","");
            startActivity(new Intent(requireContext(), VipAkomapalendInfoActivity.class));
        });
        userAvatarImageView.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("ME","AVATAR_CLICK","");
            startActivity(new Intent(requireContext(), VipAkomapalendInfoActivity.class));
        });

        //feedback
        feedbackView.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("ME","FEEDBACK_CLICK","");
            startActivity(new Intent(requireContext(), FbackActivity.class));
        });

        //privacypolicy
        agreementView.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("ME","PRIVACY_POLICY_CLICK","");
            String agreementUrl = AppAkomapalendConfigCustomize.instance().getAgreementUrl_akomapalend();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        //setting
        settingView.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("ME","SETTING_CLICK","");
            startActivity(new Intent(requireContext(), LogoutActivity.class));
        });


        //refresh
        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.fpca_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            refreshLayout.setRefreshing(false);
            HttpHelper.inst().fUSerData(this::refresh);
        });

    }

    private void refresh(){

        String userAvatarPath = PersAkomapalendonalInfo.instance().getUserAvatar();
        userLogoShow(userAvatarPath);

        String fullName = PersAkomapalendonalInfo.instance().getFullName();
        if (TextUtils.isEmpty(fullName)) userNameTextView.setText(getString(R.string.personal_no_name));
        else userNameTextView.setText(fullName);

        String gender = PersAkomapalendonalInfo.instance().getUserGender();
        if (TextUtils.isEmpty(gender)) userGenderTextView.setText(getString(R.string.personal_gender_unknown));
        else userGenderTextView.setText(gender);

        refreshLevel();

    }

    private void refreshLevel(){

        int grade = PersAkomapalendonalInfo.instance().getGrade();
        int toNextExp = PersAkomapalendonalInfo.instance().getNextGradeExp();

        switch (grade){
            case 3:
                vipBackView.setBackgroundResource(R.drawable.back_green_round_c);
                vipImageView.setBackgroundResource(R.drawable.image_diamond_3);
                vipTextView.setTextColor(requireContext().getColor(R.color.color_vip_3));
                vipNextImageView.setBackgroundResource(R.drawable.icon_item_2);
                vipExpDescTextView.setText(getString(R.string.personal_exp_max_desc));
                vipExpCpb.refresh(1,1,
                        requireContext().getColor(R.color.color_vip_bg_3),
                        requireContext().getColor(R.color.color_vip_progress_start_3),
                        requireContext().getColor(R.color.color_vip_3));
                break;
            case 2:
                vipBackView.setBackgroundResource(R.drawable.back_v2);
                vipImageView.setBackgroundResource(R.drawable.image_diamond_2);
                vipTextView.setTextColor(requireContext().getColor(R.color.color_vip_2));
                vipNextImageView.setBackgroundResource(R.drawable.icon_item_7);
                vipExpDescTextView.setText(getString(R.string.personal_exp_increase_to_vip3,toNextExp));
                vipExpCpb.refresh(200, 200-toNextExp,
                        requireContext().getColor(R.color.color_vip_bg_2),
                        requireContext().getColor(R.color.color_vip_progress_start_2),
                        requireContext().getColor(R.color.color_vip_2));
                break;
            default:
                vipBackView.setBackgroundResource(R.drawable.backage_v1);
                vipImageView.setBackgroundResource(R.drawable.image_diamond);
                vipTextView.setTextColor(requireContext().getColor(R.color.color_vip_1));
                vipNextImageView.setBackgroundResource(R.drawable.icon_item5);
                vipExpDescTextView.setText(getString(R.string.personal_exp_increase_to_vip2,toNextExp));
                vipExpCpb.refresh(100,100-toNextExp,
                        requireContext().getColor(R.color.color_vip_bg_1),
                        requireContext().getColor(R.color.color_vip_progress_start_1),
                        requireContext().getColor(R.color.color_vip_1));
        }

        vipTextView.setText(getString(R.string.personal_vip,grade));

    }

    private void userLogoShow(String imgPath){

        Runnable requestAvatarRunnable = () -> {
            if (TextUtils.isEmpty(imgPath) || !imgPath.startsWith("http")) return;
            try {
                URL url = new URL(imgPath);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode()==200){
                    InputStream inputStream = connection.getInputStream();
                    User_Avatar = AkomapaLendUtil.circleBitmap(BitmapFactory.decodeStream(inputStream));
                    requireActivity().runOnUiThread(() -> userAvatarImageView.setImageBitmap(User_Avatar));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        };



        if (User_Avatar!=null){
            userAvatarImageView.setImageBitmap(User_Avatar);
            new Thread(requestAvatarRunnable).start();
        }

        else {
            userAvatarImageView.setImageResource(R.drawable.image_black_sun);
            new Thread(requestAvatarRunnable).start();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        HttpHelper.inst().submitEvent("ME","END","");
    }

}